package cn.pengpeng.day04.topn3;

import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.codehaus.jackson.map.ObjectMapper;


public class TopN3 {
	public static class MapTask extends Mapper<LongWritable, Text, MovieBean, NullWritable>{
		ObjectMapper mapper = new ObjectMapper();
		@Override
		protected void map(LongWritable key, Text value,
				Mapper<LongWritable, Text, MovieBean, NullWritable>.Context context)
				throws IOException, InterruptedException {
			
			MovieBean bean = mapper.readValue(value.toString(), MovieBean.class);
			context.write(bean, NullWritable.get());
		}
	}
	
	public static class ReduceTask extends Reducer<MovieBean, NullWritable, MovieBean, NullWritable>{
		@Override
		protected void reduce(MovieBean key, Iterable<NullWritable> values,
				Reducer<MovieBean, NullWritable, MovieBean, NullWritable>.Context context)
				throws IOException, InterruptedException {
			int sum = 0;
			for (NullWritable nullWritable : values) {
				
				if(sum<20){
					sum++;
					context.write(key, NullWritable.get());
				}else{
					context.write(new MovieBean(), NullWritable.get());
					break;
				}
			}
			context.write(new MovieBean(), NullWritable.get());
		}
	}
	
	public static void main(String[] args) throws Exception{
		Configuration conf = new Configuration();
		Job job = Job.getInstance(conf);
		
		//设置job的map 和 reduce 是哪一个 提交任务的类
		job.setMapperClass(MapTask.class);
		job.setReducerClass(ReduceTask.class);
		job.setJarByClass(TopN3.class);
		
		//设置输出的类型
		job.setMapOutputKeyClass(MovieBean.class);
		job.setMapOutputValueClass(NullWritable.class);
		
		job.setOutputKeyClass(MovieBean.class);
		job.setOutputValueClass(NullWritable.class);
		
		job.setNumReduceTasks(2);
		job.setPartitionerClass(MyPatition.class);
		job.setGroupingComparatorClass(MyGroup.class);
		
		
		//设置输入目录和输出目录
		FileInputFormat.addInputPath(job, new Path("d:/data/rating.json"));
		FileOutputFormat.setOutputPath(job, new Path("d:/out/topn3"));
		
		
		File file = new File("d:/out/topn3");
		if(file.exists()){
			FileUtils.deleteDirectory(file);
		}
		
		//提交任务并等待任务结束，能够打印日志
		boolean waitForCompletion = job.waitForCompletion(true);
		System.out.println(waitForCompletion?"程序正常退出":"程序有问题了");
	}
}
